#include "ktota.h" 


#define ota_dbg printf
/*
#define BOOTLOADER 1
*/
#ifdef BOOTLOADER
typedef void (*app_pfunc)(void);
void ktota_jump_app(uint32_t appxaddr)
{ 
	app_pfunc app = NULL;
	/* 
	volatile unsigned long sp_addr = *(volatile unsigned long*)(appxaddr + sizeof(unsigned long) );
    printf("appaddr = %ul, sp = %ul\r\n", appxaddr, sp_addr);
    */
	INTX_DISABLE();	/* disable irq */ 
	if(((*(volatile unsigned long*)appxaddr)&0x2FF00000)==0x20000000)	/* 检查栈顶地址是否合法. */
	{ 
        MSR_MSP(*(volatile unsigned long*)appxaddr);/* 第1个字是栈顶地址 */
		app = (app_pfunc)( *(volatile unsigned long*)(appxaddr + sizeof(unsigned long)) ); /* 第2个字为app运行地址 */
		app();
        /* can't run here */
	}
}	

#endif

uint8_t verify_app_head(const uint8_t *binbuf)
{
    bin_head* bin = (bin_head*)binbuf;
	if(bin->model != dev_model){
		ota_dbg("检测到APP程序设备型号不符\r\n");
		return 0;
	}
	ota_dbg("APP程序软件版本: %d.%d\r\n", bin->version>>0x8, bin->version&0xff);
	ota_dbg("APP程序版本日期: %d\r\n", bin->buildtime);
	return 1;
}

uint8_t verify_app_data(const uint8_t *binbuf)
{
	uint8_t *appdata;
	uint32_t data_len, calval;
	bin_head *head= (bin_head*)binbuf;
	data_len = head->data_len;
	appdata = binbuf + head->head_len;
	calval = ota_calcrc32(appdata , data_len);
	ota_dbg("文件校验码0x%08X, 计算校验码0x%08X\r\n", crcval, calval);
	if(head->crc32val != calval) {
		ota_dbg("文件校验错误\r\n");
		return 0;
	}
	else {
		ota_dbg("文件校验正确\r\n");
	}
	return 1;
}


